{% extends 'html/all.html' %}
{% block title %}
    商城
{% endblock %}
{% block head_extra %}

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
          integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
    <style>
        nav[aria-label="Page navigation"] {
            position: fixed;
            right: 0;
            bottom: 0;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group">
{#                <button aria-expanded="false" class="btn btn-outline-secondary dropdown-toggle"#}
{#                        data-bs-toggle="dropdown" type="button">#}
{#                    类别#}
{#                </button>#}
                <ul class="dropdown-menu">
                </ul>
                <input class="form-control" placeholder="搜索物品" type="text"/>
                <button class="btn btn-outline-primary" type="button" id="searchButton">搜索</button>
            </div>
        </div>
    </div>
    <div class="container my-4">
        <div class="row row-cols-1 row-cols-md-3 g-4" id="productRow">
        </div>
        <!-- 分页条 -->
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
            </ul>
        </nav>
    </div>
{% endblock %}
{% block scripts %}
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>

        $(document).ready(function () {
            var currentPage = 1;
            var totalPages = 1;

            function truncateDescription(description) {
                if (description.length > 24) {
                    return description.substring(0, 24) + '...';
                } else {
                    return description;
                }
            }

            $('#productRow').fadeOut();  // 开始加载新页面时，隐藏当前的商品列表

            function getTotalCount() {
                $.ajax({
                    url: '/api/get_total_count',
                    type: 'GET',
                    success: function (response) {
                        if (response.status === 'success') {
                            totalPages = Math.ceil(response.data / 9);  // 假设每页显示9个商品
                            loadPage(1);
                        } else {
                            console.error('获取总数失败:', response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX 请求失败:', error);
                    }
                });
            }

            function loadPage(page) {
                $.ajax({
                    url: '/api/show_all',
                    type: 'GET',
                    data: {
                        page: page
                    },
                    beforeSend: function () {
                        {#$('#productRow').fadeOut();  // 开始加载新页面时，隐藏当前的商品列表#}
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            var productRow = $('#productRow');
                            productRow.empty();
                            response.data.forEach((item) => {
                                var soldText = item.IsSold ? '<span class="badge bg-danger">已售</span>' : '';
                                var btnDisabled = item.IsSold ? 'disabled' : '';
                                var detailsButton = item.IsSold ? '' : `<a class="btn btn-primary" href="/details?id=${item.ProductID}">查看详情</a>`;
                                var truncatedDescription = truncateDescription(item.Description);
                                productRow.append(
                                    `<div class="col">
                            <div class="card">
                                <img alt="产品图片" class="card-img-top" src="${item.ImageURL}"/>
                                <div class="card-body">
                                    <h5 class="card-title">${item.ProductName} ${soldText}</h5>
                                    <h5 class="card-title">${item.Category}</h5>
                                    <p class="card-text">卖家：${item.username}</p>
                                    <p class="card-text">卖家信用分：${item.Credits}</p>
                                    <p class="card-text">${truncatedDescription}</p>
                                    <p class="card-text">${item.Price}￥</p>
                                    ${detailsButton}
                                </div>
                            </div>
                        </div>`
                                );
                            });
                            currentPage = page;
                            updatePagination();
                            $('#productRow').fadeIn();  // 新页面的商品数据加载完成后，显示新的商品列表
                        } else {
                            console.error('加载产品失败:', response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX 请求失败:', error);
                    }
                });
            }

            $.ajax({
                url: '/api/get_categoryName',  // API 的 URL
                type: 'GET',
                success: function (response) {
                    if (response.status === 'success') {
                        var dropdownMenu = $('.input-group .dropdown-menu');
                        dropdownMenu.empty();  // 清空现有的菜单项
                        response.data.forEach((item) => {
                            dropdownMenu.append(`<li class="dropdown-item category-item">${item.CategoryName}</li>`);
                        });
                    } else {
                        console.error('加载类别失败:', response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX 请求失败:', error);
                }
            });
            // 将点击事件绑定到新的类上
            $(document).on('click', '.category-item', function () {
                var selectedCategory = $(this).text();
                $('.input-group .dropdown-toggle').text(selectedCategory);
            });

            $('#searchButton').click(function () {
                var searchText = $('.input-group input').val();
                var selectedCategory = $('.input-group .dropdown-toggle').text();
                // 隐藏分页条
                $('nav[aria-label="Page navigation"]').hide();
                // 发送 AJAX 请求来获取搜索结果
                $.ajax({
                    url: '/api/show_select',  // 假设这是搜索 API 的 URL
                    type: 'GET',
                    data: {
                        searchText: searchText,
                        selectedCategory: selectedCategory
                    },
                    success: function (response) {
                        if (response.status === 'success') {
                            var productRow = $('#productRow');
                            productRow.empty();
                            response.data.forEach((item) => {
                                // 更新页面的内容，显示搜索结果
                                // 这部分的代码和 loadPage 函数中的相同
                                var soldText = item.IsSold ? '<span class="badge bg-danger">已售</span>' : '';
                                var btnDisabled = item.IsSold ? 'disabled' : '';
                                var detailsButton = item.IsSold ? '' : `<a class="btn btn-primary" href="/details?id=${item.ProductID}">查看详情</a>`;
                                var truncatedDescription = truncateDescription(item.Description);
                                productRow.append(
                                    `<div class="col">
                <div class="card">
                    <img alt="产品图片" class="card-img-top" src="${item.ImageURL}"/>
                    <div class="card-body">
                        <h5 class="card-title">${item.ProductName} ${soldText}</h5>
                        <h5 class="card-title">${item.Category}</h5>
                        <p class="card-text">卖家：${item.username}</p>
                        <p class="card-text">卖家信用分：${item.Credits}</p>
                        <p class="card-text">${truncatedDescription}</p>
                        <p class="card-text">${item.Price}￥</p>
                        ${detailsButton}
                    </div>
                </div>
            </div>`
                                );
                            });
                            $('#productRow').fadeIn();  // 显示新的商品列表
                        } else {
                            console.error('搜索失败:', response.message);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX 请求失败:', error);
                    }
                });
            });

            function updatePagination() {
                var pagination = $('#pagination');
                pagination.empty();
                var maxVisiblePages = 10;  // 最多显示的页码数量
                var startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
                var endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
                startPage = Math.max(1, endPage - maxVisiblePages + 1);  // 重新计算开始页码，以确保总是显示10个页码

                for (var i = startPage; i <= endPage; i++) {
                    var li = $('<li class="page-item"></li>');
                    if (i === currentPage) {
                        li.addClass('active');
                    }
                    var a = $('<a class="page-link" href="#"></a>').text(i);
                    a.click(function (e) {
                        e.preventDefault();
                        loadPage(parseInt($(this).text()));
                    });
                    li.append(a);
                    pagination.append(li);
                }

                if (totalPages > maxVisiblePages) {
                    var ellipsis = $('<li class="page-item disabled"><a class="page-link" href="#">...</a></li>');
                    pagination.append(ellipsis);

                    var lastPage = $('<li class="page-item"></li>');
                    var lastPageLink = $('<a class="page-link" href="#"></a>').text(totalPages);
                    lastPageLink.click(function (e) {
                        e.preventDefault();
                        loadPage(totalPages);
                    });
                    lastPage.append(lastPageLink);
                    pagination.append(lastPage);

                    var select = $('<select class="form-select"></select>');
                    for (var i = 1; i <= totalPages; i++) {
                        var option = $('<option></option>').text(i);
                        if (i === currentPage) {
                            option.attr('selected', 'selected');
                        }
                        select.append(option);
                    }
                    select.change(function () {
                        loadPage(parseInt($(this).val()));
                    });
                    pagination.append(select);
                }
            }

            getTotalCount();
        });
    </script>
{% endblock %}